package com.starmark.gateway.springcloud.provider.service.impl;

import com.starmark.gateway.springcloud.provider.dto.GatewayProjectDto;
import com.starmark.gateway.springcloud.provider.service.IJwtTokenService;
import com.starmark.gateway.springcloud.provider.service.IRouteService;
import com.starmark.gateway.springcloud.provider.utils.JwtHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

/**
 * @author starmark
 * @date 20-1-23  下午10:08
 */
@Service("jwtTokenService")
public class JwtTokenServiceImpl implements IJwtTokenService {

    @Autowired
    private JwtHelper jwtHelper;

    @Autowired
    private IRouteService routeService;

    @Override
    public String createJwtToken(String userInfo, String salt, long expireTime) {
        return jwtHelper.sign(userInfo, salt, expireTime);
    }

    @Override
    public String createJwtToken(String token, String projectCode) {
        Assert.hasText(projectCode,"工程编码不存在");
        GatewayProjectDto gatewayProjectDto =routeService.getGatewayProject(projectCode);
        Assert.notNull(gatewayProjectDto,"工程不存在:"+projectCode);
        return this.createJwtToken(token, gatewayProjectDto.getSalt(), gatewayProjectDto.getExpireTime());
    }

    @Override
    public String getUserInfoByJwtToken(String jwtToken) {
        return jwtHelper.getUsername(jwtToken);
    }

    @Override
    public boolean isTokenExpired(String token) {
        return jwtHelper.isTokenExpired(token);
    }


    @Override
    public  boolean shouldTokenRefresh(String token,String  projectCode) {
        Assert.hasText(projectCode,"工程编码不存在");
        GatewayProjectDto gatewayProjectDto =routeService.getGatewayProject(projectCode);
        Assert.notNull(gatewayProjectDto,"工程不存在:"+projectCode);
        Date issueAt=jwtHelper.getIssuedAt(token);
        LocalDateTime issueTime = LocalDateTime.ofInstant(issueAt.toInstant(), ZoneId.systemDefault());
        return LocalDateTime.now().minusSeconds(gatewayProjectDto.getTokenRefreshInterval()).isAfter(issueTime);
    }
}
